08. Add State To A Component

State

Earlier in this Lesson, we learned that props refer to attributes from parent components. In the end, props represent "read-only" data that are immutable.

A component's state, on the other hand, represents mutable data that ultimately affects what is rendered on the page. State is managed internally by the component itself and is meant to change over time, commonly due to user input (e.g., clicking on a button on the page).

In this section, we'll see how we can encapsulate the complexity of state management to individual components.

Add State To Components

💡 Class Fields 💡

In the code above, we put the state object directly inside the class…not in a constructor() method!

```js
class User extends React.Component {
state = {
username: 'Tyler'
}
}

...rather than:

> ```js
class User extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     username: 'Tyler'
   };
 }
}

This is slightly different from Facebook's Setting the Initial State docs.

Having state outside the constructor() means it is a class field, which is a proposal for a new change to the language. It currently isn't supported by JavaScript, but thanks to Babel's fantastic powers of transpiling, we can use it!

Set Contacts Array As State In App

⚠️ Props in Initial State ⚠️

When defining a component's initial state, avoid initializing that state with props. This is an error-prone anti-pattern, since state will only be initialized with props when the component is first created.

this.state = {
 user: props.user
}

In the above example, if props are ever updated, the current state will not change unless the component is "refreshed." Using props to produce a component's initial state also leads to duplication of data, deviating from a dependable "source of truth."

Properties of State?

What is true about state in React? Please select all that apply:

SOLUTION:
  • A component's state can be defined at initialization.
  • State that is needed by multiple components needs to be lifted up to the closest common ancestor.
  • A component can alter its own internal state.

State Recap

By having a component manage its own state, any time there are changes made to that state, React will know and automatically make the necessary updates to the page.

This is one of the key benefits of using React to build UI components: when it comes to re-rendering the page, we just have to think about updating state. We don't have to keep track of exactly which parts of the page change each time there are updates. We don't need to decide how we will efficiently re-render the page. React compares the previous output and new output, determines what has changed, and makes these decisions for us. This process of determining what has changed in the previous and new outputs is called Reconciliation.

Further Research